<div class="layui-form-item">
    <div class="layui-inline">
        <label class="layui-form-label">名称:</label>
        <div class="layui-input-inline">
            <input type="text" name="name" id="search-role-name" autocomplete="off" placeholder="请输入名称"
                   class="layui-input">
        </div>
        <button class="layui-btn" id="search-role-btn">搜索</button>
    </div>
</div>
<script type="text/html" id="role-head-bar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="goEdit"><i class="layui-icon">&#xe654;</i>添加</button>
    </div>
</script>
<script type="text/html" id="role-role-bar">
    <a class="layui-btn layui-btn-xs" lay-event="edit-role">编辑</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="assign-menu">授权</a>
</script>
<script type="text/html" id="role-status">
    <input type="checkbox" id="status" name="status" value="{{d.id}}" lay-skin="switch" lay-text="有效|无效"
           lay-filter="status-filter" {{ d.status== 1 ? 'checked' : '' }}>
</script>
<table class="layui-table" lay-filter="role-table" id="role-table">
</table>
<script type="text/javascript">

    let treeData = [{
        id: 1,
        title: '江西' //一级菜单
        , children: [{
            title: '南昌' //二级菜单
            , children: [{
                id: 2,
                title: '高新区' //三级菜单
                //…… //以此类推，可无限层级
            }]
        }],
        icon: "fa fa-bug",
        parentId: "",
        sort: 1,
        type: 0,
        url: ""
    }
    ]
    let checkedIds = [];

    $(function () {
        //加载数据
        $.ajax({
            url: "/sys/role/menu_tree2",
            method: "get",
            success: function (packJson) {
                if (packJson) {
                    treeData = packJson;
                } else {
                    layer.message(packJson.msg)
                }
            }
        })
    })


    layui.use(["table", "layer", "form", "tree"], function () {

        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var tree = layui.tree;

        async function treeAjax(data) {
            await tree.render({
                elem: '#menu-tree'
                , data: treeData //数据源
                , spread: true //
                , id: 'demoId' //定义索引
                , showCheckbox: true //是否勾选
                // ,accordion : true //开启手风琴模式
                , onlyIconControl: true //节点左侧图标来展开收缩
            });
            if (data) {
                await $.each(data.result, function (i, obj) {
                    //给树选中
                    tree.setChecked('demoId', obj.id);
                })

            }

        }

        //调用参数menuId数组数据
        function submitCheck() {
            var checkedData = tree.getChecked('demoId'); //获取选中节点的数据
            // var nodeIds = new Array();
            getCheckedId(checkedData);
            alert(checkedIds + "sss")
            return checkedIds;
        }

        // 获取选中节点的id
        function getCheckedId(jsonObj) {
            var id = "";
            $.each(jsonObj, function (index, item) {
                if (item.children.length == 0) {
                    checkedIds.push(item.id);
                } else {
                    id = getCheckedId(item.children);
                }
            });
            console.log(checkedIds)
            // var id = "";
            // $.each(jsonObj, function (index, item) {
            //     var i;
            //     debugger;
            //     if (item.children.length == 0) {
            //         id = item.id;
            //     }else{
            //         i = item.id;
            //         getCheckedId(item.children);
            //
            //     }
            //     if (i != null&& id != "") {
            //         id = id + "," + i;
            //         alert(id+"ss")
            //     }else if( id != null){
            //         id = id + "," + id;
            //     }
            // });
            // alert(id+"==========id");
            //
            // return id;

        }

        form.on('switch(status-filter)', function (obj) {
            var status = obj.elem.checked;
            $.ajax({
                url: '/sys/role/update',
                data: "id=" + this.value + "&status=" + (status ? 1 : 0),
                method: 'post',
                success: function (result) {
                    if (result.status) {
                        layer.tips("修改成功", obj.othis);
                    } else {
                        layer.tips(result.message, obj.othis)
                    }
                }, error: function () {
                    layer.tips("修改失败", obj.othis);
                }
            })
            return;
        });
        table.render({
            id: "role-table",
            elem: '#role-table'
            , toolbar: '#role-head-bar'
            , cellMinWidth: 80
            , url: '/sys/role/table' //数据接口
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页,
                , limits: [5, 10, 15, 20, 25, 30]
                , limit: 5
            }
            , cols: [[
                {field: 'id', title: 'ID', sort: true, fixed: 'left'}
                , {field: 'name', title: '角色名'}
                , {field: 'remark', title: '备注'}
                , {
                    field: 'status', title: '状态', templet: '#role-status'
                }, {fixed: 'right', title: '操作', toolbar: '#role-role-bar', width: 180}
            ]],
            response: {
                // statusName: 'status' //规定数据状态的字段名称，默认：code
                statusCode: 200 //规定成功的状态码，默认：0
                // ,msgName: 'hint' //规定状态信息的字段名称，默认：msg
                // ,countName: 'total' //规定数据总数的字段名称，默认：count
                // ,dataName: 'rows' //规定数据列表的字段名称，默认：data
            },
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.list //解析数据列表
                };
            }


        });
        //头工具栏事件
        table.on('toolbar(role-table)', function (obj) {
            switch (obj.event) {
                case 'goEdit':
                    openEditWindow(null);
                    break;
            }
            ;
        });
        //监听行工具事件
        table.on('tool(role-table)', function (obj) {
            let data = obj.data;
            switch (obj.event) {
                case 'edit-role': {
                    openEditWindow(data);
                    break;
                }
                case 'assign-menu': {
                    layer.open({
                        type: 1,
                        content: $('#menu-tree-layer').html(),
                        title: '角色授权'
                        , area: ['400px', '600px'],
                        btn: ['提交', '取消'] //可以无限个按钮
                        , yes: function (index, layero) {
                            //树中全选和半选的都要
                            var nodes = $("#menu-tree").tree('getChecked', ['checked', 'indeterminate']);
                            // var nodeIds = submitCheck();
                            // checkedIds = [];
                            var ids = new Array();
                            $.each(nodes, function (i, obj) {
                                ids.push(obj.id);
                            })
                            $.ajax({
                                url: "/sys/role/assign_menu",
                                method: "post",
                                data: "roleId=" + data.id + "&menuIds=" + ids,
                                success: function (json) {
                                    if (json.status) {
                                        layer.close(index)
                                        layer.replace();
                                    } else {
                                        layer.message(json.message)
                                    }
                                }
                            })
                        }
                        , success: function (layero, index) {
                            // treeAjax();
                            $.ajax({
                                url: "/sys/role/role_menu",
                                method: "post",
                                data: "roleId=" + data.id,
                                success: function (json) {
                                    // if (json) {
                                    //     treeAjax(json);
                                    // }
                                    //
                                    // this.textTree = json;
                                    //勾选已经拥有的菜单
                                    $("#menu-tree").tree({
                                        url: "/sys/role/menu_tree",
                                        checkbox: true,
                                        formatter: function (node) {
                                            return node.name;
                                        }, onLoadSuccess: function (node, data) {//树加载成功之后
                                            var tree= $("#menu-tree");
                                            for(var i=0;i<json.length;i++){
                                                // debugger;
                                                var node = tree.tree('find',json[i]);
                                                console.log(node);
                                                // tree.setChecked('menu-tree',json.result[i].id)
                                                if(node!=null && tree.tree("isLeaf",node.target)){
                                                    tree.tree("check",node.target);

                                                }
                                            }
                                        }
                                    });
                                }
                            })
                        }

                    });


                    break;
                }
            }
        });

        // //执行节点勾选
        // tree.setChecked('demoId', 1); //单个勾选 id 为 1 的节点
        // tree.setChecked('demoId', [2, 3]); //批量勾选 id 为 2、3 的节点
        function openEditWindow(data) {
            layer.open({
                type: 1,
                content: $('#role-edit-layer').html(),
                title: '编辑角色'
                , area: ['500px', '300px'],
                btn: ['提交', '取消'] //可以无限个按钮
                , yes: function (index, layero) {
                    layer.load()
                    $.ajax({
                        url: 'sys/role/html?act=' + (data == null ? 'add' : 'update'),
                        data: $("#role-edit-form").serialize(),
                        method: 'post',
                        success: function (result) {
                            if (result.status) {
                                table.reload('role-table', {});
                                layer.close(index);
                            } else {
                                alert(result.message)
                            }
                            layer.closeAll('loading');
                        }
                    })
                }, success: function (layero, index) {
                    form.render()
                    if (data != null) {
                        form.val("role-edit-form", {
                            "id": data.id,
                            "name": data.name // "name": "value"
                            , "remark": data.remark,
                            "status": data.status + ""
                        });
                    }
                }
            });
        }

        $("#search-role-btn").click(function () {
            table.reload('role-table', {
                where: {
                    "name": $("#search-role-name").val()
                } //设定异步数据接口的额外参数
            });
        })

    });

</script>

<script type="text/html" id="role-edit-layer">
    <form id="role-edit-form" style="width: 80%" class="layui-form" lay-filter="role-edit-form">
        <input type="hidden" name="id">
        <div class="layui-form-item">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required" placeholder="请输入角色名" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <input type="text" name="remark" required lay-verify="required" placeholder="请输入备注" autocomplete="off"
                       class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-block">
                <input type="radio" name="status" title="有效" value="1" checked/>
                <input type="radio" name="status" title="无效" value="0"/>
            </div>
        </div>
    </form>
</script>

<script type="text/html" id="menu-tree-layer">
    <!--    <div id="menu-tree"></div>-->
    <ul id="menu-tree">


    </ul>
</script>